import Taro from "@tarojs/taro"

class Request {
  constructor() {
    this.baseUrl = ''
    this.url = ''
    this.method = 'GET'
    this.beforeRequest = null
    this.afterRequest = null
    this.header = {}
    this.options = {}
  }



  _request(url, data = {}) {
    this.url = url
    this.options = {
      baseUrl: this.baseUrl,
      url: this.baseUrl + this.url,
      path: this.url,
      method: this.method,
      header: this.header
    }
    return new Promise((resolve, reject) => {

      (!!this.beforeRequest && typeof this.beforeRequest === 'function') && this.beforeRequest(this.options)

      Taro.request({
        url: this.baseUrl + this.url,
        method: this.method,
        header: this.options.header,
        data,
        success: res => {
          resolve({ data: res.data, statusCode: res.statusCode })
        },
        fail: err => {
          reject(err)
        },
        complete: res => {
          (!!this.afterRequest && typeof this.afterRequest === 'function') && this.afterRequest(res)
        }
      })
    })
      .then(res => res)
      .catch(err => err)
  }

  get(url, data) {
    this.method = 'GET'
    return this._request(url, data)
  }
  post(url, data) {
    this.method = 'POST'
    return this._request(url, data)
  }
}

export default new Request()